/**
 * Created by three on 14-8-6.
 */
'use strict';

/**
 * socket.io
 */
angular.module('th.socket', [])
    .factory('socket', ['$rootScope', function ($rootScope) {
        var sockets = {};
        return {
            get: function (opts) {
                if (sockets[opts.url]) {
                    return sockets[opts.url];
                }
                sockets[opts.url] = window.io.connect(opts.url);

                return sockets[opts.url];
            },
            on: function (url, event_name, callback) {
                var socket = this.get({url: url});
                socket.on(event_name, function () {
                    var args = arguments;
                    $rootScope.$apply(function () {
                        callback.apply(socket, args);
                    })
                })
            },
            emit: function (url, event_name, data, callback) {
                var socket = this.get({url: url});
                console.log(socket)
                socket.emit(event_name, data, function () {
                    var args = arguments;
                    $rootScope.$apply(function () {
                        if (callback) {
                            callback.apply(socket, args)
                        }
                    });
                })
            }
        };
    }])
;
